package net.chasing.retrofit.util;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 加密拦截器
 */
public class EncryptionInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody oldBody = request.body();
        RequestBody body = null;
        if (oldBody instanceof MultipartBody) {
            body = oldBody;
        } else {
            Object[] data = writeTo(oldBody);
            if (data != null)
                body = RequestBody.create((MediaType) data[1], (String) data[0]);
        }

        Request.Builder builder = request.newBuilder()
                .header("Content-Length", body == null ? "0" : String.valueOf(body.contentLength()));
        if (body != null){
            MediaType mediaType = body.contentType();
            if (mediaType != null){
                builder.header("Content-Type", mediaType.toString());
            }
        }

        //开启method(request.method(), body)方法才会重新设置请求体，因此此方法不适合用于get
        //get要求不能拥有请求体
        if ("POST".equals(request.method()))
            builder.method(request.method(), body);
        request = builder.build();
        return chain.proceed(request);
    }

    private Object[] writeTo(RequestBody body) {
        try {
            Object[] result = new Object[2];
            Buffer buffer = new Buffer();
            MediaType mediaType = null;
            if (body != null) {
                body.writeTo(buffer);
                mediaType = body.contentType();
            }
            if (mediaType == null) {
                mediaType = MediaType.parse("application/json; charset=UTF-8");
            }
            StringBuilder stringBuffer = new StringBuilder();
            String s;
            while ((s = buffer.readUtf8Line()) != null) {
                stringBuffer.append(s);
            }
            result[0] = stringBuffer.toString().trim(); //数据，需要加密就在这里对数据进行处理
            result[1] = mediaType;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
